<template>
  <div class="home">
    <audio id="audioID" ref="audio" class="aud">
      <source controls="controls" />
    </audio>
    <el-row>
      <el-col :span="12">
        <el-input v-model="inputText"></el-input>
      </el-col>
      <el-col :span="12">
        <el-button type="primary" @click="onLoadFiles">生成音频</el-button>
      </el-col>
    </el-row>
    <!-- 滚动表格 -->
    <el-row>
      <el-carousel :interval="5000" height="520px" indicator-position="none" :loop="false" direction="vertical"
        @change="ListpageChage">
        <el-carousel-item v-for="item in ChangeList">
          <el-table v-for="item1 in item" :data="item" style="width: 100%;">
            <el-table-column prop="name" label="日期" width="180">
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="180">
            </el-table-column>
            <el-table-column prop="address" label="地址">
            </el-table-column>
          </el-table>
        </el-carousel-item>
      </el-carousel>
    </el-row>
    <!-- 只有点击一下才能使用音频 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span>点击确认使用音频</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import axios from 'axios'

export default {
  name: 'ScreenView',
  created() {
    //   let speech = new SpeechSynthesisUtterance("ewrwe");
    //  window.speechSynthesis.speak(speech);
    this.init();
    this.DoWork();
    this.DealList();
  },
  data() {
    return {
      path: "ws://127.0.0.1:9200/ws",
      socket: "",
      speechQueue: [],
      inputText: "",
      dialogVisible: true,
      audioOpen: false,
      ChangeList: [

      ]
    }
  },
  destroyed() {
    // 销毁监听
    this.socket.onclose = this.close;
  },
  methods: {
    //初始化websocket
    init: function () {
      if (typeof (WebSocket) === "undefined") {
        alert("您的浏览器不支持socket")
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    //定时消费呼叫队列
    DoWork: function () {
      let $this = this;
      setInterval(function () {
        if ($this.speechQueue.length > 0) {
          const playState = $this.$refs.audio.paused;
          console.log(playState);
          if (!playState) {
            return;
          }

          let msg = $this.speechQueue.shift();
          $this.onLoadFiles(msg);
        }
      }, 1000);
    },
    //连上服务器
    open: function () {
      console.log("socket连接服务器成功!");
      //设置自己的组别
      var parm = { action: "join", JoinRoom: "Screen" };
      this.socket.send(JSON.stringify(parm));
    },
    //连接报错
    error: function () {
      console.log("连接错误");
    },
    //获取到消息
    getMessage: function (msg) {
      console.log(msg.data);
      try {
        let msginfo = JSON.parse(msg.data);
        //判断是否为语音文字
        if (msginfo.Speak)
          this.speechQueue.push(msginfo.Speak);
      } catch (error) {
      }
    },
    close: function () {
      console.log("socket已经关闭");
    },
    //监听播放完成的回调
    audioEnded() {
      this.audioOpen = false
      console.log('end')
    },
    //通过文字获取音频Base64，播放
    onLoadFiles(msg) {
      const $this = this;
      msg = msg || $this.inputText;
      if (!msg)
        return;
      //请求
      axios({
        method: 'get',
        url: '/api/Tools/Text2Vocie',
        params: { text: msg },
        responseType: 'json'
      }).then(function (response) {
        if (response.data.code = 200) {
          let palyer = $this.$refs.audio;
          palyer.src = 'data:audio/wav;base64,' + response.data.data;
          palyer.load(); // 清除缓存，以便重新加载音频
          palyer.play(); // 播放音频
        }
      }).catch(function (error) {
        console.log(error);
      });
    }, DealList() {


      var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      var charactersLength = characters.length;

      //造假的数据
      const allList = [];
      let count = Math.random() * (10) + 20;
      for (let index = 0; index < count; index++) {
        var str = '';
        for (var i = 0; i < 2; i++) {
          str += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        const element = { name: str + "名字" + index, sex: "男", age: index, adresss: "地址" + index };
        allList.push(element);
      }
      //拆分
      const result = [];
      const size = 10;
      for (let i = 0; i < allList.length; i += size) {
        result.push(allList.slice(i, i + size));
      }
      console.log(result);
      this.ChangeList = result;
    }, ListpageChage(newinde) {

      if (this.ChangeList.length == newinde + 1) {
        //滚动到最后一页
        this.DealList();
        
      }
    }
  }
}


</script>

<style scoped>
.header {
  width: 100%;
  height: 500px;
}

.main {
  background-color: grey;
  color: white;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  height: 200px;
  padding: 20px;
  margin: 0px 2px;
  box-sizing: border-box;
}



.righttop {
  position: absolute;
  right: 0px;
  top: 0px;
  width: 100px;
  height: 40px;
  overflow: hidden;
  opacity: 0.5;
  z-index: 99;
}
</style>